// 引入连接池
var dbConfig = require('../util/dbconfig')

// 调用阿里大鱼
const Core = require('@alicloud/pop-core')
const config = require('../util/aliconfig')
// 配置
let client = new Core(config.alicould)
let requestOption = {
  method: 'POST'
};

// 随机四位验证码
function rand(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}
// 存phone,code
validatePhoneCode = [];
// 检查手机号
let sendCodeP = (phone) => {
  for (let item of validatePhoneCode) {
    if (phone === item.phone) {
      return true;
    } else {
      return false;
    }
  }
}
// 验证码匹配
let findCodeAndPhone = (phone, code) => {
  for (let item of validatePhoneCode) {
    if (phone == item.phone && code == item.code) {
      return 'login'
    } else {
      return 'error';
    }
  }
}

// 验证码登陆后检测是否是第一次登陆
let phoneLoginBind = async (phone) => {
  let sql = 'SELECT * FROM user WHERE username=? or phone=?'
  let sqlArr = [phone, phone]
  let res = await dbConfig.SySqlConnect(sql, sqlArr);
  if (res.length) {
    // 有Length已注册
    res[0].userinfo = await getUserInfo(res[0].id);
    return res;
  } else {
    // 用户第一次注册,绑定表// 用户注册
    let res = await regUser(phone);
    // 获取用户详情
    res[0].userinfo = await getUserInfo(res[0].id);
    return res;
  }
}
// 用户注册
let regUser = async (phone) => {
  // 检测用户是否第一次注册
  let userpic = `http://localhost:3000/uploads/default.png`;
  let sql = 'INSERT INTO user(username,userpic,phone) value(?,?,?)'
  let sqlArr = [phone, userpic, phone];
  let res = await dbConfig.SySqlConnect(sql, sqlArr);
  if (res.affectedRows == 1) {
    // 执行成功 获取用户信息
    let user = await getUser(phone);
    // 创建用户副表
    let userinfo = await createUserInfo(user[0].id);
    if (userinfo.affectedRows == 1) {
      return user
    } else {
      return false;
    }
  } else {
    return false;
  }
}

// 获取用户信息
let getUser = (username) => {
  let sql = 'SELECT * FROM user WHERE id=? or phone=? or username=?';
  let sqlArr = [username, username, username];
  return dbConfig.SySqlConnect(sql, sqlArr);
}

// 创建用户副表
let createUserInfo = (user_id) => {
  let sql = 'INSERT INTO userinfo(user_id,age,sex,job) values (?,?,?,?)';
  let sqlArr = [user_id, 18, 1, '未设置'];
  return dbConfig.SySqlConnect(sql, sqlArr);
}
// 获取注册的用户详情
let getUserInfo = (user_id) => {
  let sql = 'SELECT age,sex,job,path,birthday FROM userinfo WHERE user_id=?';
  let sqlArr = [user_id]
  return dbConfig.SySqlConnect(sql, sqlArr)
}
// 查看用户详情
let findUserInfo = async (user_id) => {
  let sql = 'SELECT * FROM userinfo WHERE user_id=?';
  let sqlArr = [user_id];
  let res = await dbConfig.SySqlConnect(sql, sqlArr);
  if (res.length) {
    return true
  }
  return false;
}
// 修改用户信息详情
let setUserInfo = async (user_id, age, sex, job, path, birthday) => {
  if (findUserInfo(user_id)) {
    // 如果有详情,修改update
    let sql = 'UPDATE userinfo SET age=?, sex=?, job=?, path=?, birthday=? WHERE user_id=?';
    let sqlArr = [age, sex, job, path, birthday, user_id];
    let res = await dbConfig.SySqlConnect(sql, sqlArr);
    if (res.affectedRows == 1) {
      let user = await getUser(user_id);
      let userinfo = await getUserInfo(user[0].id);
      user[0].userinfo = userinfo[0]
      return user
    } else {
      return false;
    }
  } else {
    // 如果没有详情,insert
    let sql = 'INSERT INTO userinfo (user_id, age, sex, job, path, birthday) values(?, ?, ?, ?, ?, ?)';
    let sqlArr = [user_id, age, sex, job, path, birthday];
    let res = await dbConfig.SySqlConnect(sql, sqlArr);
    if (res.length) {
      let user = await getUser(user_id);
      let userinfo = await getUserInfo(user.id);
      user[0].userinfo = userinfo[0]
      return user
    } else {
      return false;
    }
  }
}
// 修改用户名
let setUsername = async (user_id, username) => {
  let sql = 'UPDATE user SET username = ? WHERE id = ?';
  let sqlArr = [username, user_id];
  let res = await dbConfig.SySqlConnect(sql, sqlArr);
  if (res.affectedRows == 1) {
    return true
  } else {
    return false;
  }
}

// 检查用户密码
let checkUserPwd = async (user_id) => {
  let sql = 'SELECT password FROM user WHERE id = ?';
  let sqlArr = [user_id];
  let res = await dbConfig.SySqlConnect(sql, sqlArr);
  if (res.length) {
    return res[0].password;
  } else {
    return 0;
  }
}

// 大鱼发送验证码
// sendCoreCode = (req, res) => {
//   let phone = req.body.phone;
//   let code = rand(1000, 9999);
//   let params = {
//     "PhoneNumbers": phone,
//     "SignName": "",
//     "TemplateCode": "测试专用",
//     "TemplateParam": JSON.stringify({ 'code': code })
//   };
//   client.request('SendSms', params, requestOption).then((result) => {
//     console.log(result);
//     if (result.Code == 'OK') {
//       res.send({
//         code: 200,
//         msg: '发送成功'
//       });
//       validatePhoneCode.push({
//         phone: phone,
//         code: code
//       });
//       console.log(code);
//     } else {
//       res.send({
//         code: 400,
//         msg: '发送失败'
//       })
//     }
//   })
// }

// 模拟验证码发送接口
sendCode = (req, res) => {
  let phone = req.body.phone;
  if (sendCodeP(phone)) {
    res.send({
      code: 400,
      msg: '已经发送过验证码,稍后再发送'
    })
  }
  let code = rand(1000, 9999);
  validatePhoneCode.push({
    phone: phone,
    code: code
  })
  console.log(validatePhoneCode);
  res.send({
    code: 200,
    msg: '发送成功',
    data: validatePhoneCode
  })
}

// 验证码登陆接口
codePhoneLogin = async (req, res) => {
  let { phone, code } = req.body;
  console.log(req.body);
  // 该手机号是否发送过验证码
  if (sendCodeP(phone)) {
    // 验证码和手机号是否匹配
    let status = findCodeAndPhone(phone, code);
    if (status == 'login') {
      // 登陆成功
      // 登陆成功之后的操作
      let user = await phoneLoginBind(phone);
      res.send({
        code: 200,
        msg: '登陆成功',
        data: user[0]
      })
      // 登陆成功之后的操作
    } else if (status == 'error') {
      res.send({
        code: 400,
        msg: '登录失败'
      })
    }
  } else {
    res.send({
      code: 400,
      msg: '验证码发送失败'
    })
  }
}

// 用户名.手机号登陆接口
login = async (req, res) => {
  let username = req.body.username;
  let password = req.body.password;
  // let useremail = req.body.useremail;
  let phone = /^1[3-9]\d{9}$/;
  let email = /^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+.([a-zA-Z]{2,4})$/;
  if (phone.test(username)) {
    let sql = 'SELECT * FROM user WHERE phone=? and password=? or username=? and password=?';
    let sqlArr = [username, password, username, password];
    let data = await dbConfig.SySqlConnect(sql, sqlArr);
    /*if (err) {
      console.log(err);
      res.send({
        code: 400,
        msg: '出错啦'
      })
    } else*/ if (data == '') {
      res.send({
        code: 400,
        msg: '手机号或密码出错啦',
        data: []
      })
    } else {
      data[0].userinfo = await getUserInfo(data[0].id);
      res.send({
        code: 200,
        msg: '登陆成功',
        data: data
      })
    }
  } else if (email.test(username)) {
    let sql = 'SELECT * FROM user WHERE email=? and password=?';
    let sqlArr = [username, password];
    let data = await dbConfig.SySqlConnect(sql, sqlArr);
    if (data == '') {
      res.send({
        code: 400,
        msg: '邮箱或密码出错啦',
        data: []
      })
    } else {
      data[0].userinfo = await getUserInfo(data[0].id);
      res.send({
        code: 200,
        msg: '登陆成功',
        data: data
      })
    }
  } else {
    let sql = 'SELECT * FROM user WHERE username=? and password=?';
    let sqlArr = [username, password];
    let data = await dbConfig.SySqlConnect(sql, sqlArr);
    if (data == '') {
      res.send({
        code: 400,
        msg: '用户名或密码出错啦',
        data: []
      })
    } else {
      data[0].userinfo = await getUserInfo(data[0].id);
      res.send({
        code: 200,
        msg: '登陆成功',
        data: data
      })
    }
  }
}

// 修改资料接口
editUserInfo = async (req, res) => {
  let { user_id, username, age, sex, job, path, birthday } = req.body;
  let result = await setUsername(user_id, username);
  if (result) {
    let ress = await setUserInfo(user_id, age, sex, job, path, birthday);
    if (ress.length) {
      res.send({
        code: 200,
        msg: '成功',
        data: ress[0],
      })
    } else {
      res.send({
        code: 400,
        msg: '失败',
      })
    }
  } else {
    res.send({
      code: 400,
      msg: '失败',
    })
  }
}

// 修改密码接口
setPassword = async (req, res) => {
  let { user_id, oldpassword, newpassword } = req.body;
  // 检查用户密码
  let userPwd = await checkUserPwd(user_id);
  if (userPwd) {
    if (oldpassword == userPwd) {
      let sql = 'UPDATE user SET password = ? WHERE id = ?';
      let sqlArr = [newpassword, user_id];
      let result = await dbConfig.SySqlConnect(sql, sqlArr);
      if (result.affectedRows == 1) {
        res.send({
          code: 200,
          msg: '修改密码成功'
        })
      } else {
        res.send({
          code: 400,
          msg: '修改密码失败'
        })
      }
    } else {
      res.send({
        code: 200,
        msg: '旧密码不正确'
      })
    }
  } else {
    let sql = 'UPDATE user SET password = ? WHERE id = ?';
    let sqlArr = [newpassword, user_id];
    let result = await dbConfig.SySqlConnect(sql, sqlArr);
    if (result.affectedRows == 1) {
      res.send({
        code: 200,
        msg: '修改密码成功'
      })
    } else {
      res.send({
        code: 400,
        msg: '修改密码失败'
      })
    }
  }
}

// 绑定邮箱接口
bindEmail = async (req, res) => {
  let { user_id, email } = req.body;
  let sql = 'UPDATE user SET email = ? WHERE id = ?';
  let sqlArr = [email, user_id];
  let result = await dbConfig.SySqlConnect(sql, sqlArr);
  if (result.affectedRows == 1) {
    res.send({
      code: 200,
      msg: '绑定邮箱成功'
    })
  } else {
    res.send({
      code: 400,
      msg: '绑定邮箱失败'
    })
  }
}

// 退出登陆
logout = (req, res) => {
  res.send({
    code: 200,
    msg: '退出登录'
  })
}

// 修改用户头像
editUserImg = (req, res) => {
  if (!req.file) {
    res.render('error', { message: '上传文件不能为空' });
    return
  } else {
    let file = req.file;
    // console.log(file);

    //方案2: fs重命名给img
    // fs.renameSync(`./public/uploads/${file.filename}`, `./public/uploads/${file.originalname}`);
    // res.set({
    //   'content-type': 'application/json; charset=utf-8',
    // });
    let { user_id } = req.query;
    let imgUrl = `http://localhost:3000/uploads/${file.filename}`;
    // console.log(imgUrl, user_id);

    let sql = 'UPDATE user SET userpic = ? WHERE id = ?'
    let sqlArr = [imgUrl, user_id];
    dbConfig.sqlConnect(sql, sqlArr, (err, data) => {
      if (err) {
        throw err;
      } else {
        if (data.affectedRows == 1) {
          res.send({
            code: 200,
            msg: '修改成功',
            url: imgUrl,
          })
        } else {
          res.send({
            code: 400,
            msg: '修改失败',
          })
        }
      }
    })
  }
}


// 多图上传
uploadMoreImg = (req, res) => {
  if (!req.files) {
    res.render('error', { message: '上传文件不能为空' })
    return;
  } else {
    let urls = [];
    req.files.forEach(file => {
      urls.push(`http://localhost:3000/uploads/${file.filename}`);
    });
    let { user_id } = req.query
    let sql = 'INSERT INTO image(url, user_id) values(?,?)';
    let sqlArr = [urls, user_id];
    dbConfig.sqlConnect(sql, sqlArr, (err, data) => {
      if (err) {
        console.log(err);
      } else {
        if (data.affectedRows == 1) {
          res.send({
            code: 200,
            msg: '上传成功',
            data: data,
          })
        } else {
          res.send({
            code: 400,
            msg: '上传失败',
          })
        }
      }
    })
  }
}

// 视频上传
publish = async (req, res) => {
  let { user_id, title, url, path, isopen, postimg } = req.body;
  let sql = 'INSERT INTO post(user_id, title, url, path, isopen, postimg) VALUES (?, ?, ?, ?, ?, ?)';
  let sqlArr = [user_id, title, url, path, isopen, postimg];
  // 返回上传视频列表的id
  let post_id = await dbConfig.SySqlConnect(sql, sqlArr).then(res => {
    // console.log(res);
    return res.insertId
  }).catch(err => { return err });
  if (post_id) {
    res.send({
      code: 200,
      msg: '发布成功'
    })
  } else {
    res.send({ code: 400, msg: '发布失败' });
  }
}

module.exports = {
  sendCode,
  codePhoneLogin,
  // sendCoreCode,
  login,
  editUserInfo,
  setPassword,
  bindEmail,
  logout,
  editUserImg,
  uploadMoreImg,
  publish
}
/* else if (email.test(useremail)) {
    let sql = 'SELECT * FROM user WHERE email=? and password=?';
    let sqlArr = [useremail, password];
    let callBack = async (err, data) => {
      if (err) {
        console.log(err);
        res.send({
          code: 400,
          msg: '出错啦'
        })
      } else if (data == '') {
        res.send({
          code: 400,
          msg: '邮箱或密码出错啦',
          data: []
        })
      } else {
        let user_id = data[0].id;
        let result = await getUserInfo(user_id);
        data[0].userinfo = result[0];
        res.send({
          code: 200,
          msg: '登陆成功',
          data: data[0]
        })
      }
    }
    dbConfig.SySqlConnect(sql, sqlArr);
  } else {
    let sql = 'SELECT * FROM user WHERE username=? and password=?';
    let sqlArr = [username, password];
    let callBack = async (err, data) => {
      if (err) {
        console.log(err);
        res.send({
          code: 400,
          msg: '出错啦'
        })
      } else if (data == '') {
        res.send({
          code: 400,
          msg: '用户名或密码出错啦',
          data: []
        })
      } else {
        let user_id = data[0].id;
        let result = await getUserInfo(user_id);
        data[0].userinfo = result[0];
        res.send({
          code: 200,
          msg: '登陆成功',
          data: data[0]
        })
      }
    }
    dbConfig.SySqlConnect(sql, sqlArr);
  }*/
